﻿using System;
using System.Collections;
using System.Collections.Generic;
using MPBlog.Model;
using NHibernate;
using NHibernate.Criterion;

namespace MPBlog.DAL
{
    public class WidgetZoneDao : BaseDao<WidgetZone>
    {
        /// <summary>
        /// 从数据库中获得所有的zone信息
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, List<Widget>> GetAllZones()
        {
            Dictionary<string, List<Widget>> dictionary = new Dictionary<string, List<Widget>>();

            IList<string> widgetZones;
            using (ISession session = NHibernateSession)
            {
                widgetZones = session.CreateQuery("select distinct ZoneName from WidgetZone").List<string>();
            }

            foreach (string zoneName in widgetZones)
            {
                //List<ICriterion> criterions = new List<ICriterion>
                //                              { Restrictions.Eq("ZoneName", zoneName),
                //                              };
                IList<WidgetZone> zones; // = GetList(criterions, null);
                using (ISession session = NHibernateSession)
                {
                    zones = session.CreateCriteria<WidgetZone>().
                        Add(Restrictions.Eq("ZoneName", zoneName)).
                        AddOrder(new Order("DisplayIndex", true)).List<WidgetZone>();
                }

                List<Widget> list = new List<Widget>();
                foreach (WidgetZone zone in zones)
                {
                    Widget widget = new Widget
                                        {
                                            Name = zone.WidgetName,
                                            ShowTitle = zone.ShowTitle,
                                            DisplayIndex = zone.DisplayIndex,
                                            WidgetId = new System.Guid(zone.WidgetGuid)
                                        };
                    list.Add(widget);
                }
                dictionary.Add(zoneName, list);
            }

            return dictionary;
        }

        public bool DeleteByWidgetId(string widgetId)
        {
            IList<WidgetZone> widgets = GetList(Restrictions.Eq("WidgetGuid", widgetId));
            if (widgets.Count > 0)
            {
                return Delete(widgets[0]);
            }
            return false;
        }
    }
}
